import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

import Index from '@/view/index/Index'
import Login from '@/view/login/Login'
import Logout from '@/view/login/Logout'
import Home from '@/view/index/Home'
import AdminInfo from '@/view/admin/AdminInfo'
import Error from '@/view/public/Error'

Vue.use(Router)

let router=new Router({
  mode:'history',
  linkActiveClass:'active'
})

// 路由配置封装
const getRouter=(data)=>{
  let arr=[]
  for(let i in data){
    let path=data[i]['modulepath']
    let name=path.replace(/\//img,'')
    let viewname=''
    if(data[i].display==1){
      viewname='main'
    }else{
      viewname=data[i]['modulepath'].split('/')[1]
    }
    let comName=path.split('/')[2].charAt(0).toUpperCase()+path.split('/')[2].slice(1)
    let viewpath=path.split('/')[1]+'/'+comName+'.vue'   
    let obj={
      path:path,
      name:name,
      components:{[viewname]:()=>import('@/view/'+viewpath)},
      // resolve=>require(['@/view/'+viewpath],resolve)}——异步加载组件
      meta:{
        id:data[i]['id'],
        title:data[i]['modulename'],
        display:data[i]['display']
      }
    }
    arr.push(obj)
  }
  return arr
}
// 基本路由数据
let routeData=[
  {
    path:'/',
    component:Index,
    children:[
      {
        path:'/home',
        components:{main:Home},
        meta:{
          display:1,
          title:'home'
        }
      }
    ]
  },
  {
    path:'/login',
    components:{default:Login}
  },
  {
    path:'/loginout',
    components:{default:Logout}
  },
  {
    path:'/adimn/info',
    components:{default:AdminInfo}
  },
  {
    path:'*',
    components:{default:Error}
  }       
];
let module=store.state.moduleData
// 第一层路由
let levelData=getRouter(module)
// 递归生成二层路由
for(let i in module){
  if(typeof(module[i]['children'])!=undefined){
    levelData[i]['children']=getRouter(module[i]['children'])
    routeData[0]['children'].push(levelData[i])
  }
}
// 挂载路由
router.addRoutes(routeData)
// 路由卫士
router.beforeEach((to,from,next)=>{
  if(to.path.toLowerCase()!='/login'){
    if(!(store.state.adminData && store.state.adminData.id)){      
      next('/login')   
    }else{
      next()   
    }  
  }else{
    next()   
  }  
})

export default router
